import axios from 'axios'
import NProgress from 'nprogress'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false });


const baseURL = '/api'

function httpRequest() {
  NProgress.start()
  const config = {
    baseURL,
    timeout: 10000,
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    },
  }
  const user = JSON.parse(sessionStorage.getItem('user')) || {}
  if (user && user.token) {
    config.headers.token = btoa(JSON.stringify(user))
  }
  return axios.create(config)
}

function handleError(error) {
  NProgress.done()
  const data = error.response
  if ( data.status === 401) {
    // token 无效的情况
    Message.error('无权访问')
    window.location.href = '/#/login'
  } else if (data.status === 404) {
    Message.error(error.response.data.msg || '网络错误')
  } else {
    Message.error('网络错误')
  }
  return Promise.reject(error)
}

function httpGet(url, config) {
  return httpRequest().get(url, config).then((response) => {
    NProgress.done()
    return response
  }).catch(handleError)
}

function httpPut(url, data, config = {}) {
  const jsonData = JSON.stringify(data)
  return httpRequest().put(url, jsonData, ...config).then((response) => {
    NProgress.done()
    return response
  }).catch(handleError)
}

function httpPost(url, data, config = {}) {
  const jsonData = JSON.stringify(data)
  return httpRequest().post(url, jsonData, ...config).then((response) => {
    NProgress.done()
    return response
  }).catch(handleError)
}

function httpDelete(url, config = {}) {
  return httpRequest().delete(url, config).then((response) => {
    NProgress.done()
    return response
  }).catch(handleError)
}

export { baseURL, httpGet, httpPut, httpPost, httpDelete }
